package com.example.hhhh.util;

import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;

/**
 * 操作uuid工具类
 *
 * @author liangzx
 * @version 1.0
 * @time 2017-08-24 19:06
 **/
public class OperUUIDUtil {

    /**
     * 创建并读取uuid
     * @return
     */
    public synchronized static String createUUID() {
        File f = getUUIDFile();
        try {
            if (!f.exists()) {
                writeUUIDToFile(f);
            }
            return readUUIDFromFile(f);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取存储uuid的文件
     * @return
     */
    public static File getUUIDFile() {
        return new File(Environment.getExternalStorageDirectory().getAbsolutePath(), ".systemUUID");
    }

    /**
     * 删除uuid文件
     */
    public static void delUUIDFile()
    {
        getUUIDFile().delete();
    }

    /**
     * 从文件中读取uuid
     * @param file
     * @return
     * @throws IOException
     */
    public static String readUUIDFromFile(File file) throws IOException {
        RandomAccessFile f = new RandomAccessFile(file, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    /**
     * 从文件中读取uuid
     * @return
     */
    public static String readUUIDFromFile() {
        try {
            return readUUIDFromFile(getUUIDFile());
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 将uuid写入文件
     * @param file
     * @throws IOException
     */
    private static void writeUUIDToFile(File file) throws IOException {
        FileOutputStream out = new FileOutputStream(file);
        out.write(createUUIDStr().getBytes());
        out.close();
    }

    /**
     * 创建uuid
     * @return
     */
    public static String createUUIDStr() {
        return "1-" + UUID.randomUUID().toString().toUpperCase();
    }

    /**
     * 将指定的uuid写入文件
     * @param uuid
     * @throws IOException
     */
    public static void writeUUIDToFile(String uuid) {
        if (!TextUtils.isEmpty(uuid)) {
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(getUUIDFile());
                out.write(uuid.getBytes());
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
